import { Flex, Spin, message, MenuProps } from 'antd';
import { useNavigate } from 'react-router-dom';

import orchestrationService from '@/api/services/orchestrationService';
import bgLayer from '@/assets/images/background/bg-layer.png';
import { GetWorkBenhList } from '@/common';
import { formatData } from '@/utils/time';

import { SvgIcon } from '../icon';
import NotData from '../NotData';

import AppInfoModal from './components/AppInfoModal';
import AvatarDisplay from './components/AvatarDisplay';
import './work.scss';

import { useEffect, useRef, useState } from 'react';

interface WorkBoxProps {
  onType: string; // create-module，check-module
  data: Array<GetWorkBenhList>;
  items?: MenuProps['items'];
  isNoData?: boolean;
  isHaveData?: boolean;
  flag?: boolean;
  showTitle?: string;
  onToAssistant?: (e: React.MouseEvent, obj: GetWorkBenhList) => void;
  onGoToApplication?: (e: React.MouseEvent, obj: GetWorkBenhList) => void;
  setWorkItems?: (data: any) => void;
  onScroll?: () => void;
  onChangeToPage?: (data: number) => void;
  setflag?: (data: boolean) => void;
}
interface page {
  list: any[];
  pageNum: number;
  pageSize: number;
  hasMore: boolean;
}

export default function WorkBox({
  items,
  onType,
  data,
  isHaveData,
  isNoData,
  onScroll,
  flag,
  showTitle,
  setWorkItems = () => {},
  onToAssistant = () => {},
  onGoToApplication = () => {},
  setflag = () => {},
  onChangeToPage = () => {},
}: WorkBoxProps) {
  const workAllRef = useRef<HTMLDivElement>(null);
  const defaultPage = { page: 1, page_size: 10, searchText: '' };
  const [dataModuleList, setdataModuleList] = useState<Array<GetWorkBenhList>>([]);

  const [onOpen, setOnOpen] = useState<boolean>(false);
  const [template, setTemplate] = useState<any>({});

  const [manageAll, setManageAll] = useState<Array<GetWorkBenhList>>();

  const [activeIndex, setActiveIndex] = useState<number>(-1);
  const [openedDropdownId, setOpenedDropdownId] = useState<number | null>(null);
  const router = useNavigate();

  console.log('isHaveData=============', isHaveData);

  const baseStyle: React.CSSProperties = {
    height: 238,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 8,
    border: '1px dashed #E5E6EB',
    cursor: 'pointer',
    flexShrink: 0,
    fontWeight: 500,
    background: '#EEF0F4',
  };
  const baseStyle1: React.CSSProperties = {
    height: 238,
    borderRadius: 8,
    background: `url(${bgLayer}) no-repeat center top`,
    backgroundColor: '#FFF',
    backgroundSize: '50% 50%',
    border: '1px solid #ffffffe3',
    cursor: 'pointer',
    position: 'relative',
    flexShrink: 0,
  };

  // 下拉触底操作
  const Scroll = () => {
    if (workAllRef.current) {
      const height1 = workAllRef.current.clientHeight; // 可以得到我们设置的高度 (不包括滚动的高度)
      const height2 = workAllRef.current.scrollTop; // 当滚动时被卷去的高度
      const height3 = workAllRef.current.scrollHeight; // 全部的高度 包括滚动的高度
      if (height1 + height2 + 20 > height3 && !flag) {
        // 当距离底部20 则会触发
        // 加了flag 是为了防止反复触发
        setflag(true);
        // 这里进行请求
        onScroll && onScroll();

        // 成功后关闭
        // setTimeout(() => {
        //   setflag(false)
        // }, 2000)
      }
    }
  };

  useEffect(() => {
    // getPublic()
    setdataModuleList(data);
  }, [data]);

  // useEffect(() => {
  //   // 确保数据源存在且为数组
  //   if (!Array.isArray(data)) return;

  //   // 搜索逻辑
  //   const filterData = () => {
  //     const lowerSearchText = (searchText || '').toLowerCase().trim();

  //     // 空搜索时返回完整数据
  //     if (!lowerSearchText) {
  //       return data;
  //     }

  //     // 多字段搜索（示例包含 name/description）
  //     return data.filter(item => {
  //       return (
  //         (item.app_name?.toLowerCase().includes(lowerSearchText) ||
  //           (item.app_description?.toLowerCase().includes(lowerSearchText)
  //           )));
  //     });
  //   };

  //   // 更新过滤后的数据
  //   setdataModuleList(filterData());
  // }, [searchText]);

  function mouseEvent(e: number) {
    return () => {
      setActiveIndex(e);
    };
  }

  function mouseLeave() {
    return () => {
      setOpenedDropdownId(null);
      setActiveIndex(-1);
    };
  }

  return (
    <div>
      {/* <div className='my-3 mb-4'>
        {onType === 'manager'
          &&
          <WorkBase
            dataList={data}
            onFilterChange={(e: Array<GetWorkBenhList>) => {
              setManageAll(e)
            }}
          />
        }
      </div> */}
      <div
        ref={workAllRef}
        onScroll={Scroll}
        className="flex h-[500px] min-w-[290px] flex-1 flex-col overflow-auto px-2"
      >
        <Flex className="grid-module">
          <div
            style={{ ...baseStyle }}
            onClick={() =>
              onChangeToPage(showTitle == '创建智能体' ? 1 : showTitle == '创建工作流' ? 2 : 3)
            }
            className="jr-step-v2-2 jr2-step-v2-1 create-agent"
          >
            <SvgIcon icon="work-add" size={30} />
            <div className="word-color  mt-2 text-sm ">
              {showTitle == '创建智能体'
                ? '从零创建智能体'
                : showTitle == '创建工作流'
                ? '从零创建工作流'
                : '从零创建融合应用'}
            </div>
          </div>
          {Array.from(manageAll || dataModuleList).map((item: any, i) => (
            <div
              key={i}
              style={{ ...baseStyle1 }}
              className="boxs box-hover relative"
              onMouseEnter={mouseEvent(i)}
              onMouseLeave={mouseLeave()}
            >
              <div className="mt-3 flex h-[70px] items-center justify-center p-3">
                <AvatarDisplay src={item.app_logo} size={50} />
              </div>
              <div className="border-t  border-t-[#FFFFFF] bg-[#F8FAFB] px-5 pt-2">
                <div className="min-w-[50px] max-w-[180px] truncate text-base font-bold">
                  {item.app_name}
                </div>
                <div className=" mb-4 mt-2 flex items-center justify-between text-xs text-[#074B79]">
                  <div
                    className=" h-[18px] rounded-small px-[6px] text-xs"
                    style={
                      item.app_type == 'agent'
                        ? { background: '#C0F8EF', color: '#00454D' }
                        : item.app_type == 'workflow'
                        ? { background: '#E3C7FD', color: '#280976' }
                        : { background: '#BADEFF', color: '#002379' }
                    }
                  >
                    {item.app_type == 'agent'
                      ? '智能体'
                      : item.app_type == 'workflow'
                      ? '工作流'
                      : '融合应用'}
                  </div>
                  <div className=" h-5 w-2/4 truncate text-right text-xs text-[#A3A3A3]">
                    {item.user_name}
                    {item.group_name != '' && ` / ${item.group_name}`}
                  </div>
                </div>
                <div className=" line-clamp-2 h-8 overflow-hidden  text-ellipsis  text-xs text-[#4E5969]">
                  <div className="text text-xs">
                    {item.review_status === 'reject' && '驳回原因:'}
                  </div>
                  {item.review_status === 'reject' ? item.review_description : item.app_description}
                </div>
              </div>
              <div className=" flex h-10 items-center justify-between rounded-md bg-[#F8FAFB] px-5 ">
                <div className=" text-xs text-[#86909C]">{formatData(item.create_time)}</div>
              </div>
              {/* 针对模块创建的浮窗 */}
              {(onType === 'create-module' || onType === 'market') && (
                <div className="popup-content">
                  <div
                    className="popup-content-child"
                    onClick={(e) => {
                      onToAssistant(e, item);
                    }}
                  >
                    应用该模板
                  </div>
                </div>
              )}
            </div>
          ))}
        </Flex>
        {!isNoData && (
          <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
            <Spin size="large" />
          </Flex>
        )}
        {!isHaveData && <NotData iconSize={80} textClassName="text-sm" />}

        {/* 加载状态提示 */}
        {/* {flag && (
          <div className='text-center  text-[14px] text  mb-4'>数据加载中...</div>
        )} */}
        {/* 无更多数据提示 */}
        {/* {!getdata.hasMore && (
          <div className='text-center  text-[14px] text  mb-4'>没有更多数据了</div>
        )} */}
      </div>

      <AppInfoModal
        open={onOpen}
        appType={template.app_type}
        title="从模板创建应用"
        defaultAppName={template.app_name}
        defaultAppDescription={template.app_description}
        defaultAppLogo={template.app_logo}
        defaultSceneImage={template.scene_image} // 从模板中获取
        onOk={async (data) => {
          const res = await orchestrationService.createAppV2({
            app_type: 'agent',
            app_name: data.appName,
            tag: data.tag,
            app_description: data.appDescription,
            app_logo: data.appLogo,
            scene_image: data.sceneImage,
            template_app_id: template.app_id,
          });
          res.app_id &&
            orchestrationService.updateAppImage(res.app_id, {
              logo: data.appLogoList,
              scene: data.sceneImageList,
            });
          if (template.app_type === 'agent') {
            if (res.app_id) {
              router(`/apps/orchestration?appId=${res.app_id}&shareId=${res.share_id}`);
            } else {
              message.error('创建失败');
            }
          } else if (res.app_id) {
            router(`/app/workflow?appId=${res.app_id}&shareId=${res.share_id}`);
          } else {
            message.error('创建失败');
          }
        }}
        onCancel={() => {
          setOnOpen(false);
          setTemplate('');
        }}
      />
    </div>
  );
}
